package com.itic.mall.system.productjd.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itic.appbase.applications.sys.syssetting.persistence.dao.SysSettingDao;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.mobile.jd.MallJdUtils;
import com.itic.mall.system.productjd.persistence.dao.ProductJdDao;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample;

@Service
@Transactional
public class ProductJdService extends CrudService<ProductJdDao, ProductJd, ProductJdExample> {
    @Autowired 
    private ProductJdDao productJdDao;
    @Autowired 
    private SysSettingDao sysSettingDao;
    /**
     * 递归同步商品列表
     * 
     * @param pageIndex
     *            起始页码
     * @param pageSize
     *            页大小
     */
    public void syncProductList(int pageIndex, int pageSize) {
    	deleteAll();
    	
        JSONArray productList = MallJdUtils.queryProductList(pageIndex, pageSize);
        for (int i = 0; i < productList.size(); i++) {       	
            JSONObject p = productList.getJSONObject(i);
             
            String convertResult = MallJdUtils.convert("0", p.getString("sku"), p.getString("conUrlB") );
            if( null != convertResult ){
            	ProductJd model = new ProductJd();
                model.setId(IdGen.uuid());
                model.setReorder(i+1);
                model.setCreateTime(new Date());
                model.setUpdateTime(new Date());
                model.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper.get(Constants.USER_ID) : "unknown");
                model.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper.get(Constants.USER_ORG) : "unknown");
                model.setIsEffective(DBConst.TRUE);
                model.setProDesc(p.getString("proDesc"));
                model.setJdId(p.getString("jdId"));
                model.setCategoryName(p.getString("categoryName"));
                model.setGoodsInventory(p.getString("goodsInventory"));
                model.setParentId(p.getString("parentId"));
                model.setConExpireDate(p.getString("conExpireDate"));
                model.setOriPrice(p.getString("oriPrice"));
                model.setConUrl(p.getString("conUrl"));
                model.setGoodsUrl(p.getString("goodsUrl"));
                model.setConTicketPrice(p.getString("conTicketPrice"));
                model.setCommission(p.getString("commission"));
                model.setCompetitive(p.getString("competitive"));
                model.setRawId(p.getString("id"));
                model.setSku(p.getString("sku"));
                model.setConUrlB(p.getString("conUrlB"));
                model.setGoodsName(p.getString("goodsName"));
                model.setConPrice(p.getString("conPrice"));
                
                String subtractString = NumberStringHelper.subtractString(p.getString("oriPrice"), p.getString("conTicketPrice"));
                String mulString = NumberStringHelper.mulString(subtractString, p.getString("commission"));
                String divString = NumberStringHelper.divString(mulString, "100", 2);
                model.setCommissionProfit(divString);
               
                productJdDao.insert(model);
            }
            
        }
        
    }

    public void deleteAll(){
    	ProductJdExample example = new ProductJdExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
    	ProductJd productJd = new ProductJd();
    	productJd.setIsEffective("0");
    	productJdDao.updateByExampleSelective(productJd, example);
    }
    

	public ProductJd getBySku(String skuId) {
		ProductJd productJd = null;
		ProductJdExample example = new ProductJdExample();
		example.setOrderByClause("CREATE_TIME DESC");
		example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andSkuEqualTo(skuId);
		List<ProductJd> list = productJdDao.selectByExample(example);
		if( list.size()>0 ){
			productJd = list.get(0);
		}
		
		if( list.size() > 1 ){
			productJdDao.deleteByPrimaryKey(list.get(1).getId());
		}
		return productJd;
	}

	public void deleteTrueByExample(ProductJdExample example) {
		productJdDao.deleteByExample(example);
	}

	/**
	 * 获得京东二合一接口
	 * @param skuNum
	 * @param position
	 * @return
	 */
	public String getCommonLinkByDdt( String skuNum, String position ){
		String result = "";
		String initUrl = "http://develop.jhjvip.cn:8081/ddt/mobile/jdlm/getUrl?sku=";
		String byKey = sysSettingDao.getByKey("DDT_WWW_ADDRESS");
		if( StringHelper.isNotBlank(byKey) ){
			initUrl = byKey;
		}
		initUrl = initUrl + skuNum;
		
		if( StringHelper.isNotBlank(position) ){
			initUrl = initUrl+"&pid="+position;
		}
		String httpGet = HttpRequestUtils.httpGet(initUrl);
		net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(httpGet);
		String resultHttp = fromObject.getString("code");
		if( "10000".equals(resultHttp) ){
			result = fromObject.getString("data");
		}
		return result;
	}
	
	/**
	 * 获得京东优惠券接口
	 * @param skuNum
	 * @param conUrl
	 * @param position
	 * @return
	 */
	public String getConLinkByDdt( String skuNum, String conUrl, String position ){
		String result = null;
		String initUrl = "http://develop.jhjvip.cn:8081/ddt/mobile/jdlm/getConUrl?sku=";
		String byKey = sysSettingDao.getByKey("DDT_WWW_ADDRESS");
		if( StringHelper.isNotBlank(byKey) ){
			initUrl = byKey;
		}
		try {
			conUrl = URLEncoder.encode(conUrl,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		initUrl = initUrl + skuNum +"&conUrl="+conUrl;
		if( StringHelper.isNotBlank(position) ){
			initUrl += "&pid="+position;
		}
		String httpGet = HttpRequestUtils.httpGet(initUrl);
		net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(httpGet);
		String resultHttp = fromObject.getString("code");
		if( "10000".equals(resultHttp) ){
			result = fromObject.getString("data");
		}
		return result;
	}

}